//
//  CNLogManager.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2019/4/21.
//  Copyright © 2019 CSDN. All rights reserved.
//

#import "CNLogManager.h"
#import "CNLogFormatter.h"


@interface CNLogManager()

@end

@implementation CNLogManager

+ (CNLogManager *)shareManager{
    static CNLogManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CNLogManager alloc] init];
        manager.fileLogger = [[DDFileLogger alloc] init];
        manager.fileLogger.rollingFrequency = 60 * 60 * 24;                 // 刷新频率为24小时
        manager.fileLogger.logFileManager.maximumNumberOfLogFiles = 7;      // 最大文件数量为7个
        manager.fileLogger.maximumFileSize = 1024 * 1024 * 2;               // 最大文件大小
        
    });
    return manager;
}
#pragma mark - CocoaLumberjack相关方法
/**
 配置日志信息
 */
- (void)start{
    //自定义Log格式
    CNLogFormatter *logFormatter = [[CNLogFormatter alloc] init];
    
    //DDASLLogger，日志语句发送到苹果文件系统、日志状态发送到Console.app
//    [[DDASLLogger sharedInstance] setLogFormatter:logFormatter];
//    [DDLog addLogger:[DDASLLogger sharedInstance]];
    /**
     DDFileLogger，日志语句写入到文件中
     （默认路径：Library/Caches/Logs/目录下，文件名为bundleid+空格+日期.log）
     */
    
    DDFileLogger *fileLogger = [CNLogManager shareManager].fileLogger;
    [fileLogger setLogFormatter:logFormatter];
    [DDLog addLogger:fileLogger withLevel:DDLogLevelInfo];// 错误日志，写到文件中
    
    CNFileLogger *imageLogger = [[CNFileLogger alloc] initWithSavePath:@"image"];
    [imageLogger setLogFormatter:logFormatter];
    imageLogger.rollingFrequency = 60*60*24*30;
    imageLogger.logFileManager.maximumNumberOfLogFiles = 7;
    imageLogger.maximumFileSize = 1024 * 1024 * 5;
    [DDLog addLogger:imageLogger withLevel:LOG_FLAG_NETWORK_IMAGE_TIMER];// 图片请求日志，写到文件中
    
    CNFileLogger *jsonLogger = [[CNFileLogger alloc] initWithSavePath:@"json"];
    [jsonLogger setLogFormatter:logFormatter];
    jsonLogger.rollingFrequency = 60*60*24*30;
    jsonLogger.logFileManager.maximumNumberOfLogFiles = 7;
    jsonLogger.maximumFileSize = 1024 * 1024 * 5;
    [DDLog addLogger:jsonLogger withLevel:LOG_FLAG_NETWORK_JSON_TIMER];// json请求日志，写到文件中
    
    CNFileLogger *textLogger = [[CNFileLogger alloc] initWithSavePath:@"text"];
    [textLogger setLogFormatter:logFormatter];
    textLogger.rollingFrequency = 60*60*24*30;
    textLogger.logFileManager.maximumNumberOfLogFiles = 7;
    textLogger.maximumFileSize = 1024 * 1024 * 5;
    [DDLog addLogger:textLogger withLevel:LOG_FLAG_NETWORK_TEXT_TIMER];// 文本请求日志，写到文件中

    //DDTTYLogger，日志语句发送到Xcode
    [[DDTTYLogger sharedInstance] setLogFormatter:logFormatter];
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
}
- (void)didArchiveLogFile:(NSString *)logFilePath{
    
}
- (void)didRollAndArchiveLogFile:(NSString *)logFilePath{
    
}
/**
 获取日志路径(文件名bundleid+空格+日期)
 */
- (NSArray *)getAllLogFilePath:(NSString *)path{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesPath = [paths objectAtIndex:0];
    NSString *logPath = [cachesPath stringByAppendingPathComponent:path];
    NSFileManager *fileManger = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *fileArray = [fileManger contentsOfDirectoryAtPath:logPath error:&error];
    NSMutableArray *result = [NSMutableArray array];
    [fileArray enumerateObjectsUsingBlock:^(NSString *filePath, NSUInteger idx, BOOL * _Nonnull stop) {
        if([filePath hasPrefix:[NSBundle mainBundle].bundleIdentifier]){
            NSString *logFilePath = [logPath stringByAppendingPathComponent:filePath];
            [result addObject:logFilePath];
        }
    }];
    return result;
}

/**
 获取日志内容
 */
- (NSArray *)getAllLogFileContent:(NSString *)path{
    NSMutableArray *result = [NSMutableArray array];
    NSArray *logfilePaths = [self getAllLogFilePath:path];
    [logfilePaths enumerateObjectsUsingBlock:^(NSString *filePath, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [result addObject:content];
    }];
    return result;
}
/// 获取流量统计的日志str
/// @param path image text
- (NSArray *)getNetWorkLogString:(NSString *)path{
    NSMutableArray *result = [NSMutableArray array];
    NSArray *logfilePaths = [self getAllLogFilePath:path];
    __block NSString *content;
    [logfilePaths enumerateObjectsUsingBlock:^(NSString *filePath, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }];
    NSString *temp = [content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSArray *array = [temp componentsSeparatedByString:@"--*--"];
    [result addObjectsFromArray:array];
    return result;
}

- (void)uploadLogWithError:(NSError *)error{
    
}

@end
